import { useState, useEffect, useRef } from 'react';
import { AtIcon } from 'taro-ui';
import { View, Text, Input } from '@tarojs/components';
import "taro-ui/dist/style/components/icon.scss";
import css from './index.module.less';

export default function Select(props) {
    const { name, title, data, defaultValue, firstWrite, zIndex } = props;
    const [isWrite, setIsWrite] = useState(firstWrite);
    const [open, setOpen] = useState(false);
    const [value, setValue] = useState(defaultValue);
    const valueRef = useRef(null);
    const handleClick = () => {
        setOpen(!open);
    };
    const getValue = (v) => {
        setValue(v);
        setOpen(!open);
    };
    // 控制是否输入时候的字体透明度
    useEffect(() => {
        const v = valueRef.current === null ? null : valueRef.current.value;
        if (v !== null) {
            if (!v.includes("请")){
                setIsWrite(false);        
            }
        }
    }, [value]);
    return (
        <View className={css.app}>
           <Text className={css.text}>{title}</Text>
           <View className={css.select}>
               <View className={css.content} style={{zIndex: zIndex}}>
                    {open ? 
                        <View className={css.open} >
                           <Input value='请选择' disabled onClick={handleClick} />
                           {
                               data.map(item => {
                                   return <Input key={item} value={item} disabled onClick={() => getValue(item)} />;
                               })
                           }
                        </View> : 
                        <Input ref={valueRef} className={isWrite? css.firstWrite : css.write} value={value} name={name} disabled onClick={handleClick} />
                    }
               </View>
               <View className={css.icon} onClick={handleClick}>
                   {open ? 
                        <AtIcon value='chevron-up' size='25' color='#DEDDE6'></AtIcon> : 
                        <AtIcon value='chevron-down' size='25' color='#DEDDE6'></AtIcon>
                   }   
               </View>
           </View>
        </View>
    );
}
